﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using NLUNZ.Business;

namespace NLUNZ.UserControls
{
    public partial class UpdateHistory : System.Web.UI.UserControl
    {
        public List<BatchUpdateTrack> updates = new List<BatchUpdateTrack>();
        protected void Page_Load(object sender, EventArgs e)
        {
            updates = Repository.GetAllBatchUpdateTrack().ToList();
            if(Request.QueryString["id"]!=null)
            {
                int logId;
                if(int.TryParse(Request.QueryString["id"].Trim(), out logId))
                {
                    var batchUpdateTrack = updates.FirstOrDefault(u => u.UpdateTrackID == logId);
                    if (batchUpdateTrack != null)
                    {
                        string type = batchUpdateTrack.UpdateType;  
                        if(type.Equals("Delivery"))
                        {
                            Repository.DeleteDeliveryBatchRecord(logId);
                        }
                        else
                        {
                            Repository.DeleteTrackingBatchRecord(logId);
                        }
                        updates.Remove(batchUpdateTrack);
                    }
                }
            }
            string result = GetTableBody();
            tableBody.Text = result;
        }

        private string GetTableBody()
        {
            string currentUrl = HttpContext.Current.Request.Url.ToString();
            string button = "<input type='button' value='Delete' onclick='deletelog({0})' />";
            string result = string.Empty;
            string row = "<tr><td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td></tr>";
            foreach (BatchUpdateTrack batchUpdateTrack in updates)
            {
                string dt = Utility.GetDateTimeFromLogID(batchUpdateTrack.UpdateTrackID).ToString("dd/MM/yyyy HH:mm:ss");
                string action = string.Format(button, batchUpdateTrack.UpdateTrackID);
                result += string.Format(row, action, batchUpdateTrack.UpdateTrackID, batchUpdateTrack.UpdateType,dt);
            }
            return result;
        }

    }
}